package co.infinum.goldfinger.rx;

import co.infinum.goldfinger.Goldfinger;
import io.reactivex.ObservableEmitter;
import io.reactivex.annotations.NonNull;

class RxGoldfingerCallback implements Goldfinger.Callback {
    private boolean listening = true;
    @NonNull
    private final ObservableEmitter<Goldfinger.Result> emitter;

    RxGoldfingerCallback(@NonNull ObservableEmitter<Goldfinger.Result> emitter) {
        this.emitter = emitter;
    }

    public void onError(Throwable e) {
        if (!emitter.isDisposed()) {
            emitter.onError(e);
        }
    }

    @Override
    public void onResult(Goldfinger.Result result) {
        if (emitter.isDisposed()) {
            return;
        }
        if (!listening) {
            return;
        }
        listening = false;
        //刷机验证后修改
        emitter.onNext(result);
        if (result.type() == Goldfinger.Type.SUCCESS || result.type() == Goldfinger.Type.ERROR) {
            emitter.onComplete();
        }
    }

    void cancel() {
        if (!emitter.isDisposed()) {
            emitter.onComplete();
        }
    }
}
